<?php declare(strict_types=1);


namespace App\Services\Notify;


use App\Models\Store;
use App\Models\StoreAliyunAuth;

class AliYunNotifyService
{


    //app_id=2021000000000318
    //source=alipay_app_auth
    //application_type=TINYAPP,WEBAPP
    //app_auth_code=P1798b23682e34d96859afa000000003
    //{"app_id":"2021004167603274","source":"alipay_app_auth","state":"STORE_ID_VALUE","app_auth_code":"P821ebc0f499c4be496ea2978af92164"}
    public function alipay_app_auth(array $data): string
    {
        $state = $data["state"];
        //解码
        $array = json_decode($state, true);

        $store_id = $array["store_id"] ?? "";

        if (empty($store_id)) {
            throw new \Exception("店铺ID不存在");
        }

        //查询店铺

        $store = Store::query()->where("store_id", $store_id)->first();
        if (empty($store)) {
            throw new \Exception("店铺不存在");
        }


        $app_auth_code = $data["app_auth_code"];

        $auth = StoreAliyunAuth::query()->where("store_id", $store_id)->first();

        if (empty($auth)) {
            StoreAliyunAuth::query()->create([
                "store_id" => $store_id,
                "app_auth_code" => $app_auth_code
            ]);
        } else {
            $auth->app_auth_code = $app_auth_code;
        }
        return "授权成功";
    }
}